﻿using B.S.Production.ErrorCode;
using B.S.Production.Read.API.Application.Command.GetProductionOrderCommand;
using B.S.Production.Read.API.Dto;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Microsoft.AspNetCore.StaticFiles;
using B.S.Production.Read.API.Application.Command.GetMaterialsRequiredCommand;
using AutoMapper;
using System.DirectoryServices.Protocols;
using ClosedXML.Excel;
using B.S.Production.Domain.Entities;
using B.S.Production.Read.API.Application.Command.BomMainMaterialsRequiredCommand;

namespace B.S.Production.Read.API.Controllers
{
    /// <summary>
    /// Api控制器1
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ManyController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ISqlSugarClient db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="db"></param>
        /// 

        public ManyController(IMediator mediator, ISqlSugarClient db)
        {
            this.mediator = mediator;
            this.db = db;
        }
        /// <summary>
        /// 导入盘点管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            ApiResult<int> result = new ApiResult<int>();

            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = ApiEnums.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = ApiEnums.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<ProductionOrder> inventoriesList = new List<ProductionOrder>();

                        foreach (var row in rows)
                        {
                            string stateValue = row.Cell(4).GetValue<string>();
                            StatesNum stateEnum;
                            // 尝试解析状态值，若失败则默认指定一个值
                            if (!Enum.TryParse(stateValue, out stateEnum))
                            {
                                stateEnum = StatesNum.Reviewed; // 使用默认状态（需确保 `StatesNum` 中有此项）
                            }

                            var inventory = new ProductionOrder()
                           ;
                            inventory.ProductName = row.Cell(1).GetValue<string>();
                            inventory.ProductNumber = row.Cell(2).GetValue<long>();
                            inventory.Specification = row.Cell(3).GetValue<string>();
                            inventory.Unit = row.Cell(4).GetValue<string>();
                            inventory.Orderquantity = row.Cell(5).GetValue<string>();
                            inventory.ProductType = row.Cell(6).GetValue<string>();
                            inventory.StartDate = DateTime.Now;
                            inventory.EndDate = DateTime.Now;
                            inventory.DeliveryDate = DateTime.Now;
                            inventory.Remark = row.Cell(10).GetValue<string>();
                            inventory.CoId = row.Cell(11).GetValue<int>();
                            

                            // 添加到要插入的列表中
                            inventoriesList.Add(inventory);
                        }

                        // 将数据批量插入数据库
                        await db.Insertable(inventoriesList).ExecuteCommandAsync();

                        result.Code = ApiEnums.添加成功;
                        result.Msg = "导入成功";
                        result.Data = inventoriesList.Count;
                    }
                }
            }
            catch (FormatException ex)
            {
                result.Code = ApiEnums.添加失败;
                result.Msg = "导入失败，Excel 文件中数据格式错误：" + ex.Message;
                return StatusCode(500, result);
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }

            return Ok(result);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportOrderListToExcel([FromQuery] GetProductionOrderCommand command)
        {
            try
            {

                var list = (await GetProductionOrder(command)).Data;
                IWorkbook wb = new XSSFWorkbook();
                //在创建的Excel文件中创建一个工作表
                ISheet sheet = wb.CreateSheet("生产订单列表");
                //在创建的工作表中创建一行
                //注意行的序号
                IRow row = sheet.CreateRow(0);
                //在行中创建单元格 在单元格中写值
                row.CreateCell(0).SetCellValue("产品名称");
                row.CreateCell(1).SetCellValue("产品编号");
                row.CreateCell(2).SetCellValue("规格型号");
                row.CreateCell(3).SetCellValue("单位");
                row.CreateCell(4).SetCellValue("订单数量");
                row.CreateCell(5).SetCellValue("生产类型");
                row.CreateCell(6).SetCellValue("计划开工日期");
                row.CreateCell(7).SetCellValue("计划完工日期");
                row.CreateCell(8).SetCellValue("交货日期");
                row.CreateCell(9).SetCellValue("备注");
                row.CreateCell(10).SetCellValue("客户订单序号");
                //写订单信息
                //行编号
                int index = 1;
                foreach (var item in list)
                {
                    //创建新行
                    row = sheet.CreateRow(index);
                    //在行中创建单元格
                    row.CreateCell(0).SetCellValue(item.ProductName);
                    row.CreateCell(1).SetCellValue(item.ProductNumber);
                    row.CreateCell(2).SetCellValue(item.Specification);
                    row.CreateCell(3).SetCellValue(item.Unit);
                    row.CreateCell(4).SetCellValue(item.Orderquantity);
                    row.CreateCell(5).SetCellValue(item.ProductType);
                    row.CreateCell(6).SetCellValue(item.StartDate.HasValue ? item.StartDate.Value.ToString("yyyy-MM-dd") : "");
                    row.CreateCell(7).SetCellValue(item.EndDate.HasValue ? item.StartDate.Value.ToString("yyyy-MM-dd") : "");
                    row.CreateCell(8).SetCellValue(item.DeliveryDate.HasValue ? item.StartDate.Value.ToString("yyyy-MM-dd") : "");
                    row.CreateCell(9).SetCellValue(item.Remark);
                    row.CreateCell(10).SetCellValue(item.CoId);
                    //换行
                    index++;
                }
                //导出
                //excel
                byte[] buffer;
                //使用内存流出Excel的内容
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }
                //excel mine
                string excelMine = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
                return File(buffer, excelMine, "生产订单列表.xlsx");
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 生产订单查询
        /// </summary>
        /// <param name="command">实体</param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<ApiResult<List<ProductionOrder>>> GetProductionOrder([FromQuery] GetProductionOrderCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 生产订单分页
        /// </summary>
        /// <param name="command">实体</param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<ApiPaging<ProductionOrderDTO>> ShowProductionOrder([FromQuery] ShowProductionOrderCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 所需物料显示
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<MaterialsRequired>>> GetMaterialsRequired([FromQuery] GetMaterialsRequiredCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 所需物料分页显示
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiPaging<MaterialsRequiredDTO>> ShowMaterialsRequired([FromQuery] ShowMaterialsRequiredCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 基本信息分页显示
        /// </summary>
        /// <param name="command">实体</param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<ApiPaging<BomMainMaterialsRequiredDTO>> ShowBomMainMaterialsRequired([FromQuery] ShowBomMainMaterialsRequiredCommand command)
        {
            return await mediator.Send(command);
        }
    }
}
